package com.jhs.kjs.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.jhs.kjs.dto.AdminBoardPagingDTO;
import com.jhs.kjs.dto.AdminPointPagingDTO;
import com.jhs.kjs.dto.EmailDTO;
import com.jhs.kjs.dto.MenuDTO;
import com.jhs.kjs.dto.UserDTO;
import com.jhs.kjs.handler.SendMailHandler;
import com.jhs.kjs.handler.SpamPreventHandler;
import com.jhs.kjs.model.UserModel;
import com.jhs.kjs.service.IAdminBoardService;
import com.jhs.kjs.service.IAdminMemberService;
import com.jhs.kjs.service.IAdminPointService;
import com.jhs.kjs.service.IUserService;

/**
 * Handles requests for the application home page.
 */
@RequestMapping(value = "/")
@Controller
@SessionAttributes("userSessionInfo")
public class HomeController extends CommonController {

	private static final Logger logger = LoggerFactory
			.getLogger(HomeController.class);

	@Autowired
	IUserService 		userService;
	@Autowired
	IAdminBoardService 	adminBoardService;
	@Autowired
	IAdminPointService  adminPointService;
	@Autowired
	IAdminMemberService adminMemberService;
	
	@Autowired
	SendMailHandler mailSevlet;
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String rootPage() {
		
		return "redirect:/home";
	}
	
	@RequestMapping(value = "/authoSample", method = RequestMethod.GET)
	public ModelAndView authoSample(HttpServletRequest request,
			HttpServletResponse response, Locale locale, Model model) {
		ModelAndView mvc = new ModelAndView();
		mvc.setViewName("/authoritysample");

		return mvc;
	}
	
	
	@RequestMapping(value = "/mailTest", method = RequestMethod.GET)
	public ModelAndView mailTest(HttpServletRequest request,
			HttpServletResponse response, Locale locale, Model model) {
		ModelAndView mvc = new ModelAndView();
		EmailDTO email = new EmailDTO();
		email.setType("제목 ");
		email.setContents("contents");
		email.setReceiver("ponggus@naver.com");
		email.setEmail("ssam_kj@hanmail.net");
		mailSevlet.sendEmail(email);
		;

		return mvc;
	}
	

	@RequestMapping(value = "/mypage", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView mypage(Model model, HttpServletRequest request) {

		String viewName = "user/mypage";
		ModelAndView mav = new ModelAndView();
		UserDTO user = getUser(request);
		mav.addObject("user", user);
		mav.addObject("menuList", getUserBoardList());
		mav.addObject("buyTotal", adminMemberService.getBuyTotal(user.getUserId()));
		mav.addObject("useTotal", adminMemberService.getUseTotal(user.getUserId()));
		SpamPreventHandler.INSTANCE.addSpamFree(request, mav);
		
		String errorMsg = request.getParameter("msg");
		if(StringUtils.equals(errorMsg, "success")){
			errorMsg = "정상적으로 변경되었습니다.";
		}else{
			errorMsg = "";
		}
		model.addAttribute("msg", errorMsg);

		
		mav.setViewName(viewName);
		return mav;
	}

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/signin", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView signIn(HttpServletRequest request,
			HttpServletResponse response, Locale locale, Model model) {
		ModelAndView mvc = new ModelAndView("user/login");
		String errorMsg = request.getParameter("msg");
		if(StringUtils.equals(errorMsg, "true")){
			errorMsg = "아이디와 비밀번호를 확인해주세요.";
		}else{
			errorMsg = "";
		}
		mvc.addObject("msg", errorMsg);
		mvc.addObject("menuList", getUserBoardList());
		return mvc;
	}

	@RequestMapping(value = "/home", method = RequestMethod.GET)
	public ModelAndView home(HttpServletRequest request,
			HttpServletResponse response, Locale locale, Model model) {

		
		List<MenuDTO> menuList = getAllBoardList();
		
		int boardMin = Integer.MAX_VALUE;
		int boardMax = 0;
		Map<String, List<AdminBoardPagingDTO>> boardResultParam = new LinkedHashMap<String, List<AdminBoardPagingDTO>>();

		for (MenuDTO menu : menuList) {
			if (menu.getMenuType() == 0 && menu.getUseFlag() == 1) {

				Map<String, Integer> param = new HashMap<String, Integer>();
				int menuIndex = menu.getMenuIndex();
				param.put("menuIndex", menuIndex);
				List<AdminBoardPagingDTO> list = adminBoardService
						.getAdminBoardListMain(param);

				switch (menu.getMenuIndex()) {
					case 1: {
						model.addAttribute("noticeName", menu.getMenuName());
						model.addAttribute("noticeList", list);
						break;
					}
					case 2: {
						model.addAttribute("precedentName", menu.getMenuName());
						model.addAttribute("precedentList", list);
						break;
					}
					case 3: {
						model.addAttribute("lawName", menu.getMenuName());
						model.addAttribute("lawList", list);
						break;
					}
					case 4: {
						model.addAttribute("ebsName", menu.getMenuName());
						model.addAttribute("ebsList", list);
						break;
					}
				}
			}
			if (menu.getMenuType() == 1 && menu.getUseFlag() == 1) {

				boardMin = Math.min(boardMin, menu.getMenuIndex());
				boardMax = Math.max(boardMax, menu.getMenuIndex());
				setBoardList(boardResultParam, menu);
			}
		}

		model.addAttribute("boardMin", boardMin);
		model.addAttribute("boardMax", boardMax);
		model.addAttribute("boardList", boardResultParam);

		model.addAttribute("userBoardList", getUserBoardList());
		/*Map<String, Integer> param = new HashMap<String, Integer>(); 
		param.put("boardType", 1);
		model.addAttribute("boardList", adminBoardService.getAdminBoardListMain(param));
		param.put("boardType", 2);
		model.addAttribute("precedentList", adminBoardService.getAdminBoardListMain(param));
		param.put("boardType", 3);
		model.addAttribute("lawList", adminBoardService.getAdminBoardListMain(param));
		
		AdminBoardPagingDTO paging = new AdminBoardPagingDTO();
		paging.setCustom_unit(7);
		paging.setBoardType(4);
		model.addAttribute("boardList4", adminBoardService.getAdminBoardList(paging));
		
		paging.setBoardType(5);
		model.addAttribute("boardList5", adminBoardService.getAdminBoardList(paging));
		paging.setBoardType(6);
		model.addAttribute("boardList6", adminBoardService.getAdminBoardList(paging));
		paging.setBoardType(7);
		model.addAttribute("boardList7", adminBoardService.getAdminBoardList(paging));
		paging.setBoardType(8);
		model.addAttribute("boardList8", adminBoardService.getAdminBoardList(paging));
		paging.setBoardType(9);
		model.addAttribute("boardList9", adminBoardService.getAdminBoardList(paging));
		paging.setBoardType(10);
		model.addAttribute("boardList10", adminBoardService.getAdminBoardList(paging));
		paging.setBoardType(11);
		model.addAttribute("boardList11", adminBoardService.getAdminBoardList(paging));
		//EBS정보
		paging.setBoardType(-1);
		paging.setEnd(12);
		model.addAttribute("ebsList", adminBoardService.getAdminBoardList(paging));
		
		model.addAttribute("userBoardList", getUserBoardList());*/
		//System.out.println(session.getAttribute(UserModel.USER_SESSION_INFO));
		return new ModelAndView("index");
	}
	
	private void setBoardList(Map<String, List<AdminBoardPagingDTO>> map,
			MenuDTO menu) {

		AdminBoardPagingDTO paging = new AdminBoardPagingDTO();
		paging.setCustom_unit(7);
		int menuIndex = menu.getMenuIndex();
		paging.setMenuIndex(menuIndex);
		List<AdminBoardPagingDTO> list = adminBoardService.getAdminBoardList(paging);
		if (list == null) {
			list = new ArrayList<AdminBoardPagingDTO>();
		}
		map.put("boardList" + menuIndex, list);
	}
	
	@RequestMapping(value = "/afterLogin", method = RequestMethod.GET)
	public String afterLogin(HttpServletRequest request,
			HttpServletResponse response, Locale locale, Model model) {

		HttpSession session = request.getSession(false);
		session.setAttribute(UserModel.USER_INDEX , getUser(request).getUserIndex());
		session.setAttribute(UserModel.USER_LEVEL,  ""+getUser(request).getLevel());
		session.setAttribute(UserModel.USER_POINT,  ""+getUser(request).getPoint());
		session.setAttribute(UserModel.USER_SESSION_INFO, getUser(request));
		return "redirect:/home";
	}
	
	
	@RequestMapping(value = "/board/boardListMain", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView boardMain(@ModelAttribute("paging") AdminBoardPagingDTO paging){
		ModelAndView model = new ModelAndView();
		int menuIndex = paging.getMenuIndex();
		MenuDTO menu = getMenuInfo(menuIndex);
		
		String pageName = "";
		if (menu.getMenuType() == 0) {
			pageName = "user/board";

			model.addObject("noticeBoardList", getNoticeBoardList());

		} else {
			pageName = "user/board2";

			model.addObject("userBoardList", getUserBoardList());
		}

		model.setViewName(pageName);
		model.addObject("menu", menu);
		model.addObject("menuList", getUserBoardList());
		model.addObject("totalPage", adminBoardService.getAdminBoardCount(paging));
		
		return model;
	}
	
	@RequestMapping(value = "/board/getBoardList", method = RequestMethod.POST)
	public String getBoardList(HttpServletRequest req, Model model, @ModelAttribute("paging") AdminBoardPagingDTO paging){
		model.addAttribute("boardList", adminBoardService.getAdminBoardList(paging));
		model.addAttribute("totalPage", adminBoardService.getAdminBoardCount(paging));
		
		return "";
	}
	
	@RequestMapping(value = "/board/boardView", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView boardView(HttpServletRequest req, AdminBoardPagingDTO boardDTO) throws Exception{
		Map<String, Long> param = new HashMap<String, Long>();
		int menuIndex = boardDTO.getMenuIndex();
		param.put("menuIndex", Long.parseLong(String.valueOf(menuIndex)));
		param.put("textID", Long.parseLong(String.valueOf(boardDTO.getTextID())));
		
		MenuDTO menu = getMenuInfo(menuIndex);
		ModelAndView mvc = new ModelAndView();
		String view = "";
		int menuType = menu.getMenuType();
		if (menuType == 0) {
			view = "user/view";
		} else {
			view = "user/view2";
		}
		
		AdminBoardPagingDTO dto = adminBoardService.getAdminBoardView(param);
		if(menuType == 1) {
			if(getUser(req).getLevel() != 40) {
				
				Map<String, String> paramMap = new HashMap<String, String>();
				
				paramMap.put("userId", getUser(req).getUserId());
				paramMap.put("textID", String.valueOf(boardDTO.getTextID()));
				paramMap.put("usePoint", String.valueOf(dto.getUsePoint()));
				String check = adminPointService.getUsePointCheck(paramMap);
				
				//사용내역 파라미터
				AdminPointPagingDTO pointDTO = new AdminPointPagingDTO();
				pointDTO.setTextID(boardDTO.getTextID());
				pointDTO.setPoint(dto.getUsePoint());
				pointDTO.setUserId(getUser(req).getUserId());
				
				adminBoardService.updateViewCnt(param);
				//사용내역에 없음
				if(check == null) {
					//게시글의 누적 포인트 증가
					adminBoardService.updateSumPoint(param);
					//사용내역 추가
					adminPointService.insertUsePoint(pointDTO);
					//사용자포인트 차감
					userService.updateUserPoint(paramMap);
				} 
			}
			mvc.addObject("provider", adminBoardService.getProvider(param));
		} else {
			//조회수 증가
			adminBoardService.updateViewCnt(param);
		}
		dto = adminBoardService.getAdminBoardView(param);
		String content = dto.getContents();
			
		content = content.replaceAll("&lt;", "<");
		content = content.replaceAll("&gt;", ">");
		
		dto.setContents(content);
		mvc.addObject("boardView", dto);
		mvc.addObject("menu", menu);
		mvc.addObject("menuList", getUserBoardList());
		mvc.addObject("textID", boardDTO.getTextID());
		mvc.addObject("nextBoardView", adminBoardService.getNextBoardView(param));
		mvc.addObject("prevBoardView", adminBoardService.getPrevBoardView(param));
		mvc.setViewName(view);
		
		return mvc;
	}
	
	//미회원 가입자 게시글 상세보기
	@RequestMapping(value = "/board/userBoardView", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView userBoardView(HttpServletRequest req, AdminBoardPagingDTO boardDTO) throws Exception{
		Map<String, Long> param = new HashMap<String, Long>();
		int menuIndex = boardDTO.getMenuIndex();
		param.put("menuIndex", Long.parseLong(String.valueOf(menuIndex)));
		param.put("textID", Long.parseLong(String.valueOf(boardDTO.getTextID())));
		
		MenuDTO menu = getMenuInfo(menuIndex);
		ModelAndView mvc = new ModelAndView();
		String view = "";
		AdminBoardPagingDTO dto = adminBoardService.getAdminBoardView(param);
		
		String contents = dto.getContents();
		//태그삭제
		contents = contents.replaceAll("<(/)?([a-zA-Z]*)(\\s[a-zA-Z]*=[^>]*)?(\\s)*(/)?>", "").replaceAll("\r|\n| ","");
		//3줄 노출		
		contents = contents.substring(0, contents.length() / 2);
		
		dto.setContents(contents);
		logger.debug(contents);
		
		mvc.addObject("boardView", dto);
		mvc.addObject("menu", menu);
		mvc.addObject("menuList", getUserBoardList());
		mvc.addObject("textID", boardDTO.getTextID());
		mvc.addObject("nextBoardView", adminBoardService.getNextBoardView(param));
		mvc.addObject("prevBoardView", adminBoardService.getPrevBoardView(param));
		
		view = "user/userBoardView";
		mvc.setViewName(view);
		
		return mvc;
	}
	
	@RequestMapping(value = "/board/getMyInfo", method = RequestMethod.POST)
	public String getMyInfo(HttpServletRequest req, Model model, AdminBoardPagingDTO boardDTO){
		Map<String, Long> param = new HashMap<String, Long>();
		param.put("menuIndex", Long.parseLong(String.valueOf(boardDTO.getMenuIndex())));
		param.put("textID", Long.parseLong(String.valueOf(boardDTO.getTextID())));
		//게시글 정보
		AdminBoardPagingDTO dto = adminBoardService.getAdminBoardView(param);
		
		//내정보
		UserDTO user = getUser(req, true);
		model.addAttribute("boardData", dto);
		model.addAttribute("userData", user);
		
		Map<String, String> paramMap = new HashMap<String, String>();
		
		paramMap.put("userId", user.getUserId());
		paramMap.put("textID", String.valueOf(boardDTO.getTextID()));
		model.addAttribute("usePointCheck", adminPointService.getUsePointCheck(paramMap));
		return "";
	}
	
	@RequestMapping(value = "/board/ebsBoardList", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView ebsBoardList(@ModelAttribute("paging") AdminBoardPagingDTO paging){
		ModelAndView model = new ModelAndView();
		// type = 1 공지사항
		// type = 2 최신판례
		// type = 3 최신법령
		// type = 4 A항목
		// type = 5 B항목
		// type = 6 C항목
		// type = 7 D항목
		// type = 8 E항목
		// type = 9 F항목
		// type = 10 G항목
		// type = 11 H항목
		
		int boardType = paging.getBoardType();
		if (boardType == 0) {
			paging.setBoardType(1);
			boardType = 1;
		}
		
		model.setViewName("user/search_all");
		model.addObject("boardType", paging.getBoardType());
		model.addObject("boardList", adminBoardService.getEbsBoardList(paging));
		model.addObject("searchName", paging.getSearchName());
		return model;
	}
	

	@RequestMapping(value = "/board/download", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String download(HttpServletRequest request,
			HttpServletResponse response, Model model,
			AdminBoardPagingDTO boardDTO) throws Exception {
		AdminBoardPagingDTO dto = getBoardData(boardDTO);

		request.setAttribute("dto", dto);
		return "user/fileDownload";
	}

	private AdminBoardPagingDTO getBoardData(AdminBoardPagingDTO boardDTO) {
		Map<String, Long> param = new HashMap<String, Long>();
		param.put("menuIndex",
				Long.parseLong(String.valueOf(boardDTO.getMenuIndex())));
		param.put("textID",
				Long.parseLong(String.valueOf(boardDTO.getTextID())));

		AdminBoardPagingDTO dto = adminBoardService.getAdminBoardView(param);
		return dto;
	}


	@RequestMapping(value = "/pass/forgotId", method = { RequestMethod.GET})
	public ModelAndView forgotId(Model model, HttpServletRequest request) {

		return new ModelAndView("user/pop/findId");
	}



	@RequestMapping(value = "/pass/forgotPw", method = { RequestMethod.GET})
	public ModelAndView forgotPw(Model model, HttpServletRequest request) {

		return new ModelAndView("user/pop/findPw");
	}



	private String getNewPw() {
		String newPw = "";
		
		for(int i=0;i<21;i++){
			newPw+=getNewPwChar();
		}
		return newPw;
	}

	private String getNewPwChar() {
		Random r = new Random();
		
		return (char)(r.nextInt(90-64)+64)+"";
	}

	@RequestMapping(value = "/pass/findUserId", method = { RequestMethod.POST})
	public String findUserId(Model model, HttpServletRequest request) {
		Map<String, String> param = new HashMap<String, String>();
		param.put("userName", request.getParameter("userName"));
		param.put("userEmail", request.getParameter("preEmail")+"@"+request.getParameter("postEmail"));
		
		String userid = userService.findUserId(param);
		model.addAttribute("result", StringUtils.isBlank(userid)?"찾을 수 없습니다. 정보를 다시 입력해주세요.":"아이디 : "+userid);
		model.addAttribute("userId", userid);
		return "";
	}


	@RequestMapping(value = "/pass/findUserPw", method = { RequestMethod.POST})
	public String findUserPw(Model model, HttpServletRequest request) {
		Map<String, String> param = new HashMap<String, String>();
		param.put("userName", request.getParameter("userName"));
		param.put("userId", request.getParameter("userId"));
		param.put("userEmail", request.getParameter("preEmail")+"@"+request.getParameter("postEmail"));
		
		int cnt = userService.findUserPw(param);
		if(cnt>0){
			String newPs = getNewPw();
			param.put("userPw", request.getParameter("userId")+newPs);
			userService.updateUserPw(param);
			EmailDTO email = new EmailDTO();
			email.setType("알당에서 당신의 비밀번호를 초기화하였습니다. ");
			email.setContents(request.getParameter("userName")+"님 안녕하세요. 변경된 비밀번호는 "+newPs);
			//email.setReceiver(request.getParameter("preEmail")+"@"+request.getParameter("postEmail"));
			email.setReceiver("sjunghyosuc@nate.com");
			MailThread mt = new MailThread(mailSevlet);
			mt.setEmail(email);
			mt.start();
			model.addAttribute("result","이메일 주소로 변경된 비밀번호를 보냈습니다.");
		}else{
			model.addAttribute("result","정보를 다시 입력해주세요.");
			
		}
		return "";
	}

	
}
class MailThread extends Thread{
	private EmailDTO email = null;
	private SendMailHandler mailSevlet;
	public MailThread(SendMailHandler mailSevlet) {
		this.mailSevlet = mailSevlet;
	}

	public void setEmail(EmailDTO email) {
		this.email = email;
	}

	@Override
	public void run(){
		mailSevlet.sendEmail(email);
//		System.out.println("시발 메일은 언제 발송이 되는거야?? 뭐가 안맞는거야???");
	}
}